﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DalEntity
{
    public class DalGeral:IDisposable
    {
        #region Atributos
      
        ShippingEntities _db;
        Modelo.Interface.IBaseBD _basica;

        #endregion

        #region Construtor
        
        public DalGeral()
        {
            _db =  Base.GetInstance();//new ShippingEntities();
        }
        
        #endregion

        #region Métodos

        private void DefinirBase<T>(T objdeteste)
        {
            string t = objdeteste.GetType().ToString().Split('.')[1];
            _basica = (Modelo.Interface.IBaseBD)(Activator.CreateInstance("DalEntity", "DalEntity." + t)).Unwrap();// , Properties.Settings.Default.Dal + "." + "DalCliente")).Unwrap();
        }
       
        public T RetornarBasePorID<T>(int id) where T : class,new()
        {
            DefinirBase<T>(new T());
            return _basica.RetornaBasePorID<T>(id);
        }

        public IList<T> RetornarGeral<T>()  where T : class,new()
        {
            DefinirBase<T>(new T());
            return _basica.RetornaGeral<T>();
        }

        public bool Inserir<T>(T objdeteste) where T : class,new()
        {
            DefinirBase<T>(objdeteste);
            _db.AddObject(objdeteste.GetType().ToString().Split('.')[1], _basica.RetornaInstancia<T>(objdeteste)); ;
            return (_db.SaveChanges() > 0);
        }

        public bool Alterar<T>(T objdeteste) where T : class,new()
        {
            DefinirBase<T>(objdeteste);
            object persiste = _basica.RetornaInstancia<T>(objdeteste) ;
           //context.YourEntitySet.ApplyCurrentValues(newEntity);
            _db.Detach(persiste);

            
            _db.AttachTo(objdeteste.GetType().ToString().Split('.')[1],persiste);
            _db.ObjectStateManager.ChangeObjectState(persiste, EntityState.Modified);
            return (_db.SaveChanges() > 0);
        }

        public bool Excluir<T>(int id) where T : class,new()
        {
            DefinirBase<T>(new T());
            T del = (T)_basica.RetornaBasePorID<T>(id);
            object exclusao = _basica.RetornaInstancia<T>(del);
            _db.AttachTo(del.GetType().ToString().Split('.')[1], exclusao);
            
            _db.DeleteObject((exclusao));
            return(_db.SaveChanges()>0);
        }

        #endregion 
    
public void  Dispose()
{
    _db.Dispose();
    _db = null;
        
}
}
}
